
var DesTreeConfig = {
	target			: "",
	folderLinks		: true,
	useSelection	: true,
	useLines		: true,
	useIcons		: true,
	useStatusText	: false,
	useRightMenu	: true,
	closeSameLevel	: false,
	inOrder			: false,
	
	nname			: "dt_",
	cname			: "dc_",
	
	root			: "root",
	branch			: "branch",
	leaf			: "leaf",
	
	nodesel			: "NodeSelected",
	nodenor			: "NodeNormal",
	dragHander:function(thisNode,targetNode){
		return true;
	} 
};


var DesTree = Class.create(); 
/*
DesTree.imgfolder = treeImagePath;//"../static/default/images/tree/"
DesTree.icon = {
	root		: DesTree.imgfolder + 'base.gif',
	branch		: DesTree.imgfolder + 'folder.gif',
	branchOpen	: DesTree.imgfolder + 'folderopen.gif',
	leaf		: DesTree.imgfolder + 'page.gif',
	empty		: DesTree.imgfolder + 'empty.gif',
	line		: DesTree.imgfolder + 'line.gif',
	join		: DesTree.imgfolder + 'join.gif',
	joinBottom	: DesTree.imgfolder + 'joinbottom.gif',
	plus		: DesTree.imgfolder + 'plus.gif',
	plusBottom	: DesTree.imgfolder + 'plusbottom.gif',
	minus		: DesTree.imgfolder + 'minus.gif',
	minusBottom	: DesTree.imgfolder + 'minusbottom.gif',
	nlPlus		: DesTree.imgfolder + 'nolines_plus.gif',
	nlMinus		: DesTree.imgfolder + 'nolines_minus.gif',
	drag		: DesTree.imgfolder + 'move.gif',	
	branchOpen_flag: DesTree.imgfolder + 'folderopen_flag.gif',
	branch_flag	:DesTree.imgfolder + 'folder_flag.gif',
	folderleaf	: DesTree.imgfolder + 'folderleaf.gif',
	folderleaf_flag:DesTree.imgfolder + 'folderleaf_flag.gif',
	emptyspace	: 18
};

*/
DesTree.icon = {
	root		: treeimgfolder + 'base.gif',
	branch		: treeimgfolder + 'folder.gif',
	branchOpen	: treeimgfolder + 'folderopen.gif',
	leaf		: treeimgfolder + 'page.gif',
	empty		: treeimgfolder + 'empty.gif',
	line		: treeimgfolder + 'line.gif',
	join		: treeimgfolder + 'join.gif',
	joinBottom	: treeimgfolder + 'joinbottom.gif',
	plus		: treeimgfolder + 'plus.gif',
	plusBottom	: treeimgfolder + 'plusbottom.gif',
	minus		: treeimgfolder + 'minus.gif',
	minusBottom	: treeimgfolder + 'minusbottom.gif',
	nlPlus		: treeimgfolder + 'nolines_plus.gif',
	nlMinus		: treeimgfolder + 'nolines_minus.gif',
	drag		: treeimgfolder + 'move.gif',	
	branchOpen_flag: treeimgfolder + 'folderopen_flag.gif',
	branch_flag	:treeimgfolder + 'folder_flag.gif',
	folderleaf	: treeimgfolder + 'folderleaf.gif',
	folderleaf_flag:treeimgfolder + 'folderleaf_flag.gif',
	emptyspace	: 18
};

var DesTreeNode = Class.create(); 
DesTreeNode.prototype = { 
  initialize: function(id,iid, pid,type, txt, flag, sel, url,  title, target, icon, iconOpen,isopen) { //iid is innerID
	this.id = id;
	this.iid = iid;
	this.pid = pid || -1;
	this.type = type || DesTreeConfig.branch;
	this.url = url || "javascript:void(0)";
	this.txt = txt || "Tree Node";
	this.target = target || null;
	this.icon = icon;
	this.iconOpen = iconOpen;
	this.containerid = "";
	this._flg = flag || false; // use flag
	this._del = false;
	this._io = isopen || false;
	this._is = false; //┃
	this._ls = false; //┗
	this._hc = false;
	this._selected = sel || false;
	//this._ai = iid;
	this._p;
  }
};


	

DesTree.prototype = { 
	initialize: function(treeName,roottxt) { 	
		this.id 				= treeName.toString();
		this.obj 				= treeName;
		this.aNodes 			= [];
		this.aIndent 			= [];
		this.root 				= new DesTreeNode(-1,0,null,DesTreeConfig.root,roottxt||"");
		this.root._io 			= true;
		this.aNodes[this.aNodes.length] = this.root;
		this.selectedNodes 		= [{iid:this.root.iid,id:this.root.id}];
		this.selectedFound 		= false;
		this.completed 			= false;
		
		this.useMultiSelection 	= false;
		this.useCheckBox		= false;
		this.editable			= false;
		this.dragable			= false;
		this.useflag			= false;
		this.ghost				= null;
		this.overNode			= null;
		this.container			= null;
	},
	add: function(id,pid,type, txt, flag, sel, url, title, target, icon, iconOpen, open) {
		var cn = new DesTreeNode(id,this.aNodes.length, pid,type, txt, flag, sel, url, title, target, icon, iconOpen, open);
		cn.containerid = DesTreeConfig.cname + this.id + cn.id;
		if(sel)
			this.selectedNodes.push({iid:cn.iid,id:cn.id});
		this.aNodes[this.aNodes.length] = cn;		
		if(cn.pid != null){
			$(DesTreeConfig.cname + this.id + cn.pid).innerHTML += this.drawNode(cn);
		}	
		
	},
	
	openAll : function() {
		this.oAll(true);
	},
	
	closeAll : function() {
		this.oAll(false);
	},
	
	toString: function(){
		var str = '<div class="destree" id="' + this.id + '">\n';
		//str += this.addNodes(this.root);
		str += this.drawNode(this.root);
		str += '</div>';
		this.completed = true;
		return str;
	},	

	drawNode: function(node){
		var cb = "";
		if(this.editable){
			this.useMultiSelection = false;
			this.useCheckBox = false;
		}

		if(this.useCheckBox){

			if(this.useMultiSelection){
				cb = "<input type='checkbox' name='" + DesTreeConfig.nname + this.id + "_cb' id='" + DesTreeConfig.nname + this.id + "_cb" + node.iid + "' onclick='" + this.obj  + ".oc(" + node.iid + ")' ";
				if(node._selected){
					cb += "checked=true";	
				}
				cb += "/>";
			}
			else{
				if(node.type == DesTreeConfig.leaf){
					cb = "<input type='radio' name='" + DesTreeConfig.nname + this.id + "_cb' id='" + DesTreeConfig.nname + this.id + "_cb" + node.iid + "' onclick='" + this.obj  + ".oc(" + node.iid + ")' "
					if(node._selected){
						cb += "checked=true";	
					}
					cb += "/>";
				}
			}
		}
		var str = "<div id='" + (DesTreeConfig.nname + this.id) + node.id + "' iid='" + node.iid + "' ";
		str += ">";
		str += cb;
		if (DesTreeConfig.useIcons) {
			if(node.type == DesTreeConfig.root ){
				str += "<img id='" + (DesTreeConfig.nname + this.id) + node.id + "_img' src='" + DesTree.icon.root + "' onclick='" + this.obj + ".iclick(this.parentNode.id)'/>"
			}
			if(node.type == DesTreeConfig.branch ){
				str += "<img id='" + (DesTreeConfig.nname + this.id) + node.id + "_img'  src='";
				if(this.useflag){
					if(node._flg)
						str += (node._io?DesTree.icon.branchOpen_flag:DesTree.icon.branch_flag) + "'";
					else
						str += (node._io?DesTree.icon.branchOpen:DesTree.icon.branch) + "'";
				}
				else{
					str += (node._io?DesTree.icon.branchOpen:DesTree.icon.branch) + "'";
				}
				str += " onclick='" + this.obj + ".iclick(this.parentNode.id)'/>";		
			}
			if(node.type == DesTreeConfig.leaf ){
				var imgsrc = "";
				if(this.useflag){
					if(node._flg)
						imgsrc = DesTree.icon.folderleaf_flag;	
					else
						imgsrc = DesTree.icon.folderleaf;
					
				}else{
					imgsrc = DesTree.icon.leaf;
				}
				str += "<img id='" + (DesTreeConfig.nname + this.id) + node.id + "_img'  src='" + imgsrc + "'";
				str += " onclick='" + this.obj + ".iclick(this.parentNode.id)'/>";				
			}
		}
		if(!this.editable)
			str += "<span class='NodeSpan' id='" + (DesTreeConfig.nname + this.id) + node.id + "_sp' iid='" + node.iid + "' onclick='" + this.obj + ".oc(" + node.iid + ")'>";
		else
			str += "<span class='NodeSpan' id='" + (DesTreeConfig.nname + this.id) + node.id + "_sp' iid='" + node.iid + "' onclick='" + this.obj + ".iclick(this.parentNode.id);" + this.obj + ".s(" + node.iid + ");" + this.obj + ".clickHandler();' >";
		str += node.txt;
		str += "</span>"
		
		// add drag function
		if(this.dragable && node.type != DesTreeConfig.root ){
			str += "<span class='dragIcon' onmousedown='" + this.obj + ".dragNode(event,this," + node.iid + ");'>&nbsp;&nbsp;&nbsp;</span>"
			//str += "<img style='width:100px;height:20px;cursor:move;' src='" + DesTree.icon.drag + "' onmousedown='" + this.obj + ".dragNode(event,this," + node.iid + ");'/> "
		}
		
		str += "</div>";
		if(node.type == DesTreeConfig.root || node.type == DesTreeConfig.branch){
			var vis = node._io?"block":"none"
			str += "<div id='" + (DesTreeConfig.cname + this.id) + node.id + "' iid='" + node.iid + "' style='display:" + vis + ";margin-left:" + DesTree.icon.emptyspace  + "px'>";
			str += "</div>";
		}
		return str;
	},

	
	
	iclick : function(id){
		var cid = id.replace(DesTreeConfig.nname,DesTreeConfig.cname);
		var iid = $(id).getAttribute("iid");
		var tn = this.aNodes[iid];
		if(!$(cid))
			return;
		$(cid).style.display = tn._io?'none':"";		
		if(tn.type == DesTreeConfig.branch){
			if(tn._flg)
				$(id + "_img").src = tn._io?DesTree.icon.branch_flag:DesTree.icon.branchOpen_flag;
			else
				$(id + "_img").src = tn._io?DesTree.icon.branch:DesTree.icon.branchOpen;
		}
		tn._io = tn._io?false:true;
		//this.clickHandler();
		//this.s(iid)
	},
	
	
	setCS : function(node) {
		var lastId;
		for (var n=0; n<this.aNodes.length; n++) {
			if (this.aNodes[n].pid == node.iid) node._hc = true;
			if (this.aNodes[n].pid == node.pid) lastId = this.aNodes[n].iid;
		}
		if (lastId==node.iid) 
			node._ls = true;
	},
	
	// node on click;
	oc:function(iid){		
		var cn = this.aNodes[iid];		
		if (DesTreeConfig.useSelection){
			if(this.useMultiSelection){
				cn._selected = cn._selected?false:true;
				this.sc(cn,cn._selected);
			}
			else{
				//if(cn.type== DesTreeConfig.leaf){
				cn._selected = true;	
				this.s(iid);
				//}
			}
		}		
		this.clickHandler();
	},
	
	clickHandler : Function,
	
	// Select node
	s :function(iid) {
		if (!DesTreeConfig.useSelection) return;
		var cn = this.aNodes[iid];
		if(!this.useMultiSelection){
			
			var eNew = null;
			var eOld = null;
			if(this.selectedNodes.length){
				if (this.selectedNodes[0].iid != iid||this.selectedNodes[0].iid != null) {
					if (this.selectedNodes[0].iid || this.selectedNodes[0].iid==0){
						eOld = $(DesTreeConfig.nname + this.id + this.aNodes[this.selectedNodes[0].iid].id);
						this.aNodes[this.selectedNodes[0].iid]._selected = false;
						eOld.className = DesTreeConfig.nodenor;
					}
					eNew = $(DesTreeConfig.nname + this.id + cn.id);				
					eNew.className = DesTreeConfig.nodesel;
					this.selectedNodes[0] = {iid:cn.iid,id:cn.id};
					cn._selected = true;
				}
			}else
			{
				this.selectedNodes[0] = {iid:cn.iid,id:cn.id};
			}
			if(this.useCheckBox){
				if(!this.userMultiSelection){
					if(cn.type == DesTreeConfig.leaf)
						$(DesTreeConfig.nname + this.id + "_cb" + iid).checked = true;
				}
			}			
		}			
	},
	
	// Select Children
	sc : function(pnode,sel){			
		this.selNode(pnode.iid,sel)
		if(pnode.type != DesTreeConfig.leaf){
			var ns = $(DesTreeConfig.cname + this.id + pnode.id).getElementsByTagName("div");	
			for(var i=0;i<ns.length;i++){			
				if(ns[i].getAttribute("iid") && ns[i].id.indexOf(DesTreeConfig.cname)<0){
					var iid = ns[i].getAttribute("iid");
					this.selNode(iid,sel);
					
				}	
			}
		}
		this.selectedNodes = [];	
		this.getSelected();
		
	},
	
	selNode : function(iid,sel)
	{
		this.aNodes[iid]._selected = sel;
		eNew = $(DesTreeConfig.nname + this.id + this.aNodes[iid].id);	
		eNew.className = sel? DesTreeConfig.nodesel : DesTreeConfig.nodenor;
		if(this.useCheckBox)
		{
			$(DesTreeConfig.nname + this.id + "_cb" + iid).checked = sel;
		}
	},	
	
	editNode: function(id,value){
		var iid = $(DesTreeConfig.nname + this.id + id).getAttribute("iid");
		this.aNodes[iid].txt = value;
		$((DesTreeConfig.nname + this.id) + this.aNodes[iid].id + "_sp").innerHTML = value;
	},
	
	delNode: function(id){
		var iid = $(DesTreeConfig.nname + this.id + id).getAttribute("iid");
		this.aNodes[iid]._del = true;
		$(DesTreeConfig.nname + this.id + id).outerHTML = "";
		if($(DesTreeConfig.cname + this.id + id)){
			var p = $(DesTreeConfig.cname + this.id + id);
			var chs = p.getElementsByTagName("div");
			for(var i=0;i<chs.length;i++){
				if(chs[i].getAttribute("iid")){
					var ciid = chs[i].getAttribute("iid")
					this.aNodes[ciid]._del = true;
				}
			}
			p.outerHTML = "";
		}
		this.selectedNodes = [{iid:this.root.iid,id:this.root.id}];
	},
	
	setFlag: function(id,flg){
		if(!this.useflag)
			return false;
		
		var iid = $(DesTreeConfig.nname + this.id + id).getAttribute("iid");
		
		if(this.aNodes[iid].type == DesTreeConfig.root)
			return false;
			
		this.aNodes[iid]._flg = flg;
		
		var imgsrc = "";				
		
		if(flg){
			if(this.aNodes[iid].type == DesTreeConfig.leaf)
				imgsrc = DesTree.icon.folderleaf_flag;	
			else
				imgsrc = this.aNodes[iid]._io?DesTree.icon.branchOpen_flag:DesTree.icon.branch_flag;
		}
		else{
			if(this.aNodes[iid].type == DesTreeConfig.leaf)
				imgsrc = DesTree.icon.folderleaf;
			else
				imgsrc = this.aNodes[iid]._io?DesTree.icon.branchOpen:DesTree.icon.branch;
		}
		$((DesTreeConfig.nname + this.id) + id + "_img").src = imgsrc;
		//$((DesTreeConfig.nname + this.id) + this.aNodes[iid].id + "_sp").innerHTML = value;
	
	},
	
	getSelected:function(){
		var result = [];
		for(var i=0;i<this.aNodes.length;i++){
			var cn = this.aNodes[i];
			if(cn._selected && !cn._del){
				this.selectedNodes.push({iid:cn.iid,id:cn.id});	
				result.push(cn.id);
			}	
		}	
		return result;
	},
	
	getSelectedNode:function(){
		var result = [];
		for(var i=0;i<this.aNodes.length;i++){
			var cn = this.aNodes[i];
			if(cn._selected && !cn._del){
				this.selectedNodes.push({iid:cn.iid,id:cn.id});	
				result.push({id:cn.id,txt:cn.txt});
			}	
		}	
		return result;
	},
	
	getTree:function(){
		var result = [];
		for(var i=0;i<this.aNodes.length;i++){
			var cn = this.aNodes[i];
			if(!cn._del){
				result.push(cn);
			}	
		}	
		return result;
	},
	// private functions
	o : function(iid) {
		var cn = this.aNodes[iid];
		
		//this.nodeStatus(!cn._io, iid, cn._ls);
		//cn._io = !cn._io;
		//if (DesTreeConfig.closeSameLevel) this.closeLevel(cn);
		//if (DesTreeConfig.useCookies) this.updateCookie();
	},
	
	oAll : function(status) {
		for (var n=0; n<this.aNodes.length; n++) {
			if (this.aNodes[n]._hc && this.aNodes[n].pid != this.root.iid) {
				this.nodeStatus(status, n, this.aNodes[n]._ls)
				this.aNodes[n]._io = status;
			}
		}
	},
	
	createGhost: function(){
		this.ghost = document.createElement("div");
		this.ghost.id = this.id + "_gh";
		this.ghost.className = "NodeGhost";
		this.ghost.style.display ="none";
		if(_isIE)
			this.ghost.style.filter= "alpha(opacity=" + 50 + ")";
		else
			this.ghost.style.opacity= "0." + 5;
		document.body.appendChild(this.ghost);
	},
	
	dragNode:function(event,dragobj,iid){
		dragobj.style.position = "absolute";
		var id = this.id;
		var nodes = this.aNodes;
		var container = this.container;
		var gho = this.ghost;
		var offset = [0,0]
	//	if(!_isIE)
		//	offset = [container.scrollLeft,-container.scrollTop];

		var ondrag = function(){
			gho.style.display = "";
			gho.style.left = dragobj.style.left;
			gho.style.top = dragobj.style.top;
		}
		var ondrop = function(ev){			
			gho.style.display = "none";
			dragobj.style.position = "static";	
			dragobj.style.left = "auto";
			dragobj.style.top = "auto";
			gho.style.left = "auto";
			gho.style.top = "auto";		
		}
		var onrelease = function(event){
			var ps=DesTree.stopDrag(event,ondrop);
			ps = [ps[0] + container.scrollLeft,ps[1] + container.scrollTop]
			for(var i=0;i<nodes.length;i++){
				if(!nodes[i]._del && nodes[i].type != DesTreeConfig.leaf){
					var cn = nodes[i];
					var n = $(DesTreeConfig.nname + id + cn.id);
					var npos = CommonFunctions.getAbsPoint(n);
					if(ps[1]>npos.y && ps[1]<n.offsetHeight + npos.y){
						if(cn.id != nodes[iid].pid){
							//$("txtNode").value = (cn._lv + "   " + nodes[iid]._lv);
							if(nodes[iid].type == DesTreeConfig.branch){
								//$("txtNode").value = (DesTreeConfig.cname + id + nodes[iid].pid  + "   " + cn.iid);
								if(checkChild($(DesTreeConfig.cname + id + nodes[iid].id ),cn.iid))
									return;
								nodes[iid].pid = cn.id;
								//if(nodes[iid].id != nodes[iid].pid && nodes[iid]._lv >=cn._lv){
								if(nodes[iid].id != nodes[iid].pid){	
									if(!DesTreeConfig.dragHander(nodes[iid],cn)){
										return;
									}								
									CommonFunctions.cutNodeInto($(DesTreeConfig.nname + id + nodes[iid].id),$(DesTreeConfig.cname + id + nodes[iid].pid ));
									CommonFunctions.cutNodeInto($(DesTreeConfig.cname + id + nodes[iid].id),$(DesTreeConfig.cname + id + nodes[iid].pid ));
								}
							}							
							if(nodes[iid].type == DesTreeConfig.leaf){
								nodes[iid].pid = cn.id;
								if(!DesTreeConfig.dragHander(nodes[iid],cn)){
									return;
								}
								CommonFunctions.cutNodeInto($(DesTreeConfig.nname + id + nodes[iid].id),$(DesTreeConfig.cname + id + cn.id))
							}
						}
					}
				}
			}
		}
		
		var checkChild = function(pnode,iid){
			var chn = pnode.getElementsByTagName("div");
			for(var j=0;j<chn.length;j++){
				if(chn[j].getAttribute("iid")==iid){
					return true;	
				}
			}
			return false;
		}

		//this.ghost.style.left = CommonFunctions.getAbsPoint(dragobj).x + "px";
		//this.ghost.style.top = CommonFunctions.getAbsPoint(dragobj).y + "px";
		//var offset = [-CommonFunctions.getAbsPoint(dragobj).x,-CommonFunctions.getAbsPoint(dragobj).y]
		DesTree.startDrag(event,dragobj,null,ondrag,offset);
		document.onmouseup = function(event){onrelease(event)}
	}
	
	
	
};


DesTree.startDrag = function(ev,target,r,moveevent,offset,limit){
	ev 				= ev || window.event;
	var obj 		= Event.element(ev);
	var x=0,y=0;
	//if(_isIE){
	//	x = ev.layerX || ev.offsetX;
	//	y = ev.layerY || ev.offsetY;
	//}
	var offrange 	= !offset?[0,0]:offset;

	document.onmousemove = function(ev){
		ev 		= ev || window.event;
		var hp 	= vp = 0;
		var hx 	= Event.pointerX(ev) - offrange[0] - x;
		var vy 	= Event.pointerY(ev) - offrange[1] - y;
		hp 		= !r?hx:(hx<r[0]?r[0]:hx>r[1]?r[1]:hx);
		vp 		= !r?vy:(vy<r[2]?r[2]:vy>r[3]?r[3]:vy);
		target.style.left 	= hp + "px";
		target.style.top 	= vp + "px";			
		
		if(moveevent)
			moveevent();

	}
	if(!limit && _isIE){
		if(document.body.setCapture)
			document.body.setCapture();
		else if(window.captureEvents)
			window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);		
	}
	if(_isIE) document.onselectstart = function(){return false};//IE
	else ev.preventDefault();//firefox/sofari 

}
	


DesTree.stopDrag = function(ev,stopmoveevent){
	ev 		= ev || window.event;
	var obj = Event.element(ev);

	var hx 	= Event.pointerX(ev);
	var vy 	= Event.pointerY(ev);

	if(stopmoveevent)
		stopmoveevent();
	if(document.body.releaseCapture)
		document.body.releaseCapture();
	else if(window.captureEvents)
		window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);
	document.onmousemove 	= null;
	document.onmouseup		= null;
	if(CommonFunctions._isIE){
		document.onselectstart = function(){return true};
	}
	return [hx,vy]
}